<template>
  <div style="border: 1px solid #e4e4e7" class="rounded-[4px] bg-white">
    <Toolbar class="p-[4px]" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <div style="border-bottom: 1px solid #e4e4e7"></div>
    <Editor
      style="overflow-y: hidden"
      :style="'height:' + height + 'px;'"
      class="p-[4px]"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onBeforeUnmount, type PropType, ref, shallowRef, watch } from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import { ElMessage } from 'element-plus'
import { isNull, isUndefined } from 'lodash-es'
import { objKeyAes } from '@/utils/gloab'
type InsertFnType = (url: string, alt: string, href: string) => void
const emit = defineEmits(['update:modelValue'])

const props = defineProps({
  modelValue: {
    type: String,
  },
  //模式   default默认 simple简洁
  mode: {
    type: String as PropType<'default' | 'simple'>,
    default: 'default',
  },
  // 请求接口
  api: {
    type: String,
    default: '/admin-api/common/upload',
  },
  // 上传时附带的额外参数
  params: {
    type: Object,
    default: {
      ossUrl: '/common',
    },
  },
  // 高度
  height: {
    type: Number,
    default: 400,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  /**是否对参数排序加密 */
  isKeyAes: {
    type: Boolean,
    default: true,
  },
  /**请求头信息 */
  headers: {
    type: Object,
    default: {},
  },
})
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
let valueHtml = ref<string>('')
const paramsComp = computed(() => {
  let data = props.isKeyAes ? objKeyAes(props.params) : props.params
  return data
})
const editorConfig = {
  placeholder: '请输入内容',
  MENU_CONF: {
    uploadImage: {
      server: props.api,
      fieldName: 'files',
      maxNumberOfFiles: 10,
      meta: paramsComp.value,
      headers: props.headers,
      customInsert(res: any, insertFn: InsertFnType) {
        // res 即服务端的返回结果
        // console.log("res", res);
        if (res.code == 0) {
          // 从 res 中找到 url alt href ，然后插入图片
          insertFn(res.data.filePath, res.data.fileName, res.data.fileName)
        } else {
          ElMessage.warning({
            message: res.data || '上传失败',
          })
        }
      },
    },
  },
}
watch(
  () => props.modelValue,
  (val: any) => {
    if (isUndefined(val) || isNull(val)) {
      valueHtml.value = ''
    } else {
      valueHtml.value = val
    }
  },
  {
    deep: true,
    immediate: true,
  },
)
watch(
  () => valueHtml.value,
  (val: any) => {
    if (val == '<p><br></p>') {
      emit('update:modelValue', null)
    } else {
      emit('update:modelValue', val)
    }
  },
  {
    deep: true,
    immediate: true,
  },
)
watch(
  () => props.disabled,
  (val: boolean) => {
    nextTick(() => {
      // console.log("editorRef.value", val, editorRef.value);
      if (val) {
        editorRef.value.disable()
      } else {
        editorRef.value.enable()
      }
    })
  },
  {
    deep: true,
    immediate: true,
  },
)

// 工具栏配置
const toolbarConfig = {
  excludeKeys: ['insertLink', 'group-video'],
}

// function formatToken(token: null | string) {
//   return token ? `Bearer~~${token}` : null
// }
// 模拟 ajax 异步获取内容
// onMounted(() => {});
const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  // nextTick(() => {
  //   const toolbar = DomEditor.getToolbar(editorRef.value);

  //   const curToolbarConfig = toolbar.getConfig();
  //   console.log(curToolbarConfig.toolbarKeys); // 当前菜单排序和分组
  // });
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  // console.log('组件销毁时，也及时销毁编辑器');

  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style lang="scss" scoped></style>
